<?php

namespace app\Http\Controllers\admins;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class Comment extends Controller
{
    // 表单
    private function form($field = [])
    {
        $form = [
            ['label' => '评论者', 'name' => 'name', 'placeholder' => '匿名', 'value' => $this->userName()],
            ['label' => '评论内容', 'name' => 'comment', 'type' => 'textarea', 'verify' => 'required', 'placeholder' => '请输入'],
            ['label' => '状态', 'name' => 'status', 'type' => 'radio', 'value' => 0, 'options' => [0 => '正常', 1 => '待审核', 2 => '垃圾评论']],
        ];
        if ($field) {
            if (count($field) === count($field, 1)) {
                array_push($form, $field);
            } else {
                $form = array_merge($form, $field);
            }
        }
        return $form;
    }

    // 评论用户
    private function userName()
    {
        $user = Auth::user();
        if (isset($user->username))
            return $user->username;
        return '游客';
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {
            // $page = $request->page ?? 1;
            $limit = $request->limit ?? 10;
            $db = DB::table('comment')->where('post_id', '>', 0);
            // 搜索
            if (isset($request->search) && $request->search) {
                foreach ((array)$request->search as $k => $v) {
                    if ($k === 'status') {
                        if (strlen($v)) $db = $db->where($k, $v);
                    } else {
                        if ($v) $db = $db->where($k, 'like', "%{$v}%");
                    }
                }
            }
            $db = $db->orderBy('id', 'desc');
            $data['count'] = $db->count();
            // 分页
            $db = $db->paginate($limit)->items();
            if ($data['count']) {
                $data['code'] = 0;
            } else {
                $data['code'] = 1;
                $data['msg'] = '暂无记录';
            }
            $ids = array_column($db, 'post_id');
            $articles = DB::table('article')->whereIn('id', $ids)->format('id');
            $data['data'] = array_map(function ($item) use ($articles) {
                $item->title = isset($articles[$item->post_id]) ? $articles[$item->post_id]->title : '';
                $item->comment = mb_strimwidth(strip_tags($item->comment), 0, 60, '...', 'utf-8');
                $item->status = $item->status === 0 ? '正常' : ($item->status === 1 ? '待审核' : '垃圾评论');
                return $item;
            }, $db);
            return json_encode($data);
        }
        $form = [
            ['label' => '搜索ID', 'name' => 'id', 'layui' => 'inline', 'placeholder' => '请输入'],
            ['label' => '评论', 'name' => 'comment', 'layui' => 'inline', 'placeholder' => '请输入'],
            ['label' => '筛选', 'name' => 'status', 'type' => 'select', 'layui' => 'inline', 'value' => '', 'options' => ['' => '&mdash; 全部 &mdash;', 0 => '正常', 1 => '待审核', 2 => '垃圾评论']],
            ['type' => 'submit', 'filter' => 'search', 'layui' => 'inline', 'value' => '<i class="layui-icon layui-icon-search"></i>']
        ];
        $data['search'] = $this->build_form($form);
        $data['title'] = '评论列表';
        $data['prefix'] = '/admins/comment';
        return view('/admins/comment/index', $data);
    }

    public function add(Request $request)
    {
        $post_id = $request->post_id;
        if (!$post_id) return $this->errMsg(1, '数据错误');
        $data['title'] = '添加';
        $form = $this->form([
            ['name' => 'post_id', 'type' => 'hidden', 'value' => (int)$post_id],
            ['type' => 'submit', 'value' => '保存'],
            ['type' => 'button', 'value' => '取消', 'filter' => 'cancel', 'btn' => 'primary']
        ]);
        $args = ['url' => '/admins/comment/save', 'reload' => 'parent.location'];
        $data['form'] = $this->build_form($form);
        $data['script'] = $this->build_script($form, $args);
        return view('/admins/comment/add', $data);
    }

    public function save(Request $request)
    {
        $post_id = $request->post_id;
        if (!$post_id) return $this->errMsg(1, '数据错误');
        $data = $this->check($this->form(), $request);
        if (!is_array($data)) return $data;
        $check = DB::table('comment')->where('comment', $request->comment)->first();
        if ($check) return $this->errMsg(1, '评论已存在');
        $data['post_id'] = (int)$post_id;
        $user = Auth::user();
        $setting = DB::table('setting')->where('names', 'setting')->first();
        $setting = isset($setting->values) ? json_decode($setting->values) : null;
        if (!isset($data['name'])) $data['name'] = isset($user->username) ? $user->username : ($request->name ? $request->name : '游客');
        if (!isset($data['status'])) $data['status'] = isset($user->username) ? 0 : 1;
        if (!isset($data['pid'])) $data['pid'] = (int)$request->pid;
        $comment_id = DB::table('comment')->insertGetId($data);
        if (!$comment_id) $this->errMsg(1, '发布失败');
        $level = (int)$request->level;
        if ($data['pid']) $level++;
        $comment = '<div class="layui-row" style="margin-bottom: 15px;">
        <div class="layui-col-md12">
            <div class="layui-panel" style="padding: 10px 15px 0 15px;">
                <div class="layui-row layui-col-space15">
                    <div class="layui-col-sm1 layui-col-xs2">
                        <img src="' . ($user->avatar ?? ($setting->avatar ?? '')) . '" alt="avatar" style="width: 100%;padding-top: 5px;">
                    </div>
                    <div class="layui-col-sm11 layui-col-xs10">
                        <div class="layui-row">
                            <div class="layui-col-sm12">
                                <strong>' . strip_tags($data['name']) . '</strong> <cite>' . ($level ? '回复' : '说道') . '：</cite>
                            </div>
                        </div>
                        <div class="layui-row">
                            <div class="layui-col-sm12" style="margin-bottom: 10px">' . strip_tags($data['comment']) . ($data['status'] ? '（评论正在等待审核...）' : '') . '</div>
                        </div>
                        ' . ($level < ($data['setting']->commentsLevel ?? 5) ? '<div class="layui-row">
                        <div class="layui-col-sm12" style="text-align: right;margin-bottom: 15px;"><a href="javascript:;" title="留言" data-id=' . $comment_id . ' data-level=' . $level . ' class="layui-btn layui-btn-sm layui-btn-primary btn-replay"><i class="layui-icon layui-icon-at"></i> 回复</a></div>
                    </div>' : '') . '
                    </div>
                </div>
            </div>
        </div>
    </div>';
        return $this->errMsg(0, $data['status'] ? '等待审核' : '发布成功', ['comment' => $comment]);
    }

    public function edit(Request $request)
    {
        $id = (int)$request->id;
        if (!$id) return $this->errMsg(1, '数据错误');
        $value = DB::table('comment')->where('id', $id)->first();
        $form = $this->form([
            ['name' => 'id', 'type' => 'hidden', 'value' => $id],
            ['type' => 'submit', 'value' => '保存'],
            ['type' => 'button', 'value' => '取消', 'filter' => 'cancel', 'btn' => 'primary']
        ]);
        $args = ['url' => '/admins/comment/save_edit', 'reload' => 'dataTable'];
        $data['title'] = '编辑';
        $data['form'] = $this->build_form($form, $value);
        $data['script'] = $this->build_script($form, $args);
        return view('/admins/comment/edit', $data);
    }

    public function save_edit(Request $request)
    {
        $id = (int)$request->id;
        if (!$id) return $this->errMsg(1, '数据错误');
        $data = $this->check($this->form(), $request);
        if (!is_array($data)) return $data;
        DB::table('comment')->where('id', $id)->update($data);
        return $this->errMsg(0, '修改成功');
    }

    public function del(Request $request)
    {
        $id = (array)$request->id;
        if (!$id) return $this->errMsg(1, '请选择数据');
        $db = DB::table('comment');
        $all = $db->get()->all();
        $ids = $id;
        // 删除评论同时删除所有子评论
        foreach ($id as $_id) {
            $ids = array_reduce($this->trees($all, $_id), function ($res, $next) {
                $res[] = $next->id;
                return $res;
            }, $ids);
        }
        $res = $db->whereIn('id', array_unique($ids))->delete();
        if (!$res) return $this->errMsg(1, '删除失败');
        return $this->errMsg(0, '删除成功');
    }

    // 批量待审核
    public function pending(Request $request)
    {
        $id = (array)$request->id;
        if (!$id) return $this->errMsg(1, '请选择数据');
        DB::table('comment')->whereIn('id', $id)->update(['status' => 1]);
        return $this->errMsg(0, '操作成功');
    }

    // 批量垃圾评论
    public function spam(Request $request)
    {
        $id = (array)$request->id;
        if (!$id) return $this->errMsg(1, '请选择数据');
        DB::table('comment')->whereIn('id', $id)->update(['status' => 2]);
        return $this->errMsg(0, '操作成功');
    }

    // 批量审核通过
    public function passed(Request $request)
    {
        $id = (array)$request->id;
        if (!$id) return $this->errMsg(1, '请选择数据');
        DB::table('comment')->whereIn('id', $id)->update(['status' => 0]);
        return $this->errMsg(0, '操作成功');
    }
}
